package com.hl.relearndagger2.presenter;


import com.hl.relearndagger2.ShowResultView;


public class ComputerPresenter {
    private ShowResultView showResultView;
    private StringBuffer stringBuffer = new StringBuffer();

    private double firstNumberD;
    private double secondNumberD;

    public ComputerPresenter(ShowResultView showResultView)
    {
        this.showResultView = showResultView;
    }

    private boolean passCheck(String firstNumber,String secondNumber,String operator)
    {
        if (firstNumber.length() == 0)
        {
            showResultView.showErrorPrompt("第一个数为空");
            return false;
        }

        if (secondNumber.length() == 0)
        {
            showResultView.showErrorPrompt("第二个数为空");
            return false;
        }

        if (operator.equals("#"))
        {
            showResultView.showErrorPrompt("操作符为空");
            return false;
        }

        if (operator.equals("/") && Integer.parseInt(secondNumber) == 0)
        {
            showResultView.showErrorPrompt("除数不能为0");
            return false;
        }


        try
        {
            firstNumberD = Double.parseDouble(firstNumber);
            secondNumberD = Double.parseDouble(secondNumber);
        }catch (NumberFormatException e)
        {
            showResultView.showErrorPrompt("输入了非数字字符");
            return false;
        }


        return true;
    }

    public void compute(String firstNumberStr,String  secondNumberStr,String operator)
    {
        if (!passCheck(firstNumberStr,secondNumberStr,operator))
        {
            return;
        }

        switch (operator)
        {
            case "+":
                showResultView.showResult(stringBuffer.append(firstNumberD + secondNumberD).toString());
                break;
            case "-":
                showResultView.showResult(stringBuffer.append(firstNumberD - secondNumberD).toString());
                break;
            case "*":
                showResultView.showResult(stringBuffer.append(firstNumberD * secondNumberD).toString());
                break;
            case "/":
                showResultView.showResult(stringBuffer.append(firstNumberD / secondNumberD).toString());
                break;
        }

        stringBuffer.delete(0,stringBuffer.length());
    }
}
